//
//  xiugaiViewController.m
//  随便点
//
//  Created by MWJ on 15/3/25.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "xiugaiViewController.h"
#import "xiugaiTableViewCell.h"
#import "dizliebiao.h"
#import "dituTableViewCell.h"
#import "DropDown1.h"
#import "DropDown2.h"
#import "BMapKit.h"
#import "TourLocation.h"
#import "goodsViewController.h"
#import "AppDelegate.h"
#define Kdizhi @"http://www.51anys.com:8080/waimaiwang/user/address"
#define tjxg @"http://www.51anys.com:8080/waimaiwang/user/editAddress"
#define Sheng @"http://www.51anys.com:8080/waimaiwang/user/address/province"
#define Shi @"http://www.51anys.com:8080/waimaiwang/user/address/city"
#define DiQu @"http://www.51anys.com:8080/waimaiwang/user/address/area"
@interface xiugaiViewController (){
    NSString *mz;
    NSMutableArray *array;
    NSMutableArray *lbarray;
    NSDictionary *dic;
    NSDictionary *dic1;
    NSDictionary *dic2;
    NSDictionary *dic3;
    NSMutableArray *shengarray;
    NSMutableArray *shiarray;
    NSMutableArray *quarray;
    BMKMapView *_mapview;
    BMKLocationService* _locService;
    CLLocationManager *locationm;
    UIButton *button;
    BMKPointAnnotation* pointAnnotation;
    NSString *jingdu;
    NSString *weidu;
    NSMutableArray *arr1;
    NSMutableArray *arr2;
    NSMutableArray *arr3;
    NSString *code;
    NSString *code1;
    NSString *code2;
    AppDelegate *app;
    NSString *ssq;
    NSString *yb;
    NSString *dh;
    NSString *sj;
    NSString *dz;
    NSString *s;
    NSString *city;
    NSString *quyu;
    NSString *ssss;
    NSString *ssss1;
    UIAlertView *_alert;
    
}

@end

@implementation xiugaiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    sj = app._phone;
    [self xiala];
    [self ditu];
    lbarray = [NSMutableArray array];
    array = [NSMutableArray array];
    arr1 = [NSMutableArray array];
    arr2 = [NSMutableArray array];
    arr3 = [NSMutableArray array];
    if ([app._dizhiID isEqualToString:@""]||app._dizhiID == nil) {
        [self loading];
    }else{
        [self loading1];
    }
    self.tableview.dataSource = nil;
    [self shengbianhao];
    if (code1 == nil||[code1 isEqualToString:@""]) {
    }else{
        [self qubianhao];
    }
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)xiala{
    DropDown1 *d1 = [[DropDown1 alloc]initWithFrame:CGRectMake(53, 250,[UIScreen mainScreen].bounds.size.width-68, 30)];
    d1.tableArray = arr1;
    d1.textField.text = s;
    self.shengfen =d1.textField.text;
    [self.view addSubview:d1];
    
    DropDown1 *d2 = [[DropDown1 alloc]initWithFrame:CGRectMake(53, 290, [UIScreen mainScreen].bounds.size.width-68, 30)];
    d2.tableArray = arr2;
    d2.textField.text = city;
    self.shiqu = d2.textField.text;
    [self.view addSubview:d2];
    
    DropDown1 *d3 = [[DropDown1 alloc]initWithFrame:CGRectMake(53, 330, [UIScreen mainScreen].bounds.size.width-68, 30)];
    d3.tableArray = arr3;
    d3.textField.text = quyu;
    self.diyu = d3.textField.text;
    [self.view addSubview:d3];
}
-(void)ditu{
    button = [[UIButton alloc]initWithFrame:CGRectMake(0, 160, 40, 40)];
    [button setImage:[UIImage imageNamed:@"currentloc"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(dingwei) forControlEvents:UIControlEventTouchUpInside];
    _mapview = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
    _mapview.zoomLevel = 15;
    _mapview.delegate = self;
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
//    [_locService startUserLocationService];
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _jingdu = userLocation.location.coordinate.latitude;
    _weidu = userLocation.location.coordinate.longitude;
    jingdu = [NSString stringWithFormat:@"%f",_jingdu];
    weidu = [NSString stringWithFormat:@"%f",_weidu];
    [_locService stopUserLocationService];
    _mapview.userTrackingMode = BMKUserTrackingModeNone;
    BMKGeoCodeSearch *search = [[BMKGeoCodeSearch alloc]init];
    search.delegate=self;
    BMKReverseGeoCodeOption *rever = [[BMKReverseGeoCodeOption alloc]init];
    rever.reverseGeoPoint = userLocation.location.coordinate;
    [self setShowMapLongitude:_weidu latitude:_jingdu];
}
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    self.dizhi.text = result.address;
}
-(void)dingwei{
    //启动LocationService
    [_locService startUserLocationService];
}
-(void)setShowMapLongitude:(double)longitude latitude:(double)latitude{
    //设置经纬度
    CLLocationCoordinate2D coord={latitude,longitude};
    //设置显示范围精度
    BMKCoordinateSpan span={0.05,0.05};
    //显示范围
    BMKCoordinateRegion region={coord,span};
    //给地图设置显示区域
    [_mapview setRegion:region animated:YES];
    TourLocation *tourLocation=[[TourLocation alloc]init];
    tourLocation.coordinate=CLLocationCoordinate2DMake(latitude,longitude);
    self.coordinate = CLLocationCoordinate2DMake(latitude,longitude);
    _mapview.zoomLevel = 17;
//    [_mapview showsUserLocation];
    [_mapview addAnnotation:tourLocation];
}
-(void)loading{
    NSURL *url=[NSURL URLWithString:Kdizhi];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"id=%@",self.goodsID];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
        NSString *shr;
        NSString *shrdh;
        NSString *shryb;
        NSString *shrsf;
        NSString *shrcs;
        NSString *shrdq;
        NSString *shrdz;
        if (dic[@"name"] == nil||[dic[@"name"] isEqualToString:@""]) {
            shr = @"";
        }else{
            shr = dic[@"name"];
        }
        self.name.text = [NSString stringWithFormat:@"%@",shr];
        if (dic[@"mobile"] == nil||[dic[@"mobile"] isEqualToString:@""]) {
            shrdh = @"";
        }else{
            shrdh = dic[@"mobile"];
        }
        self.dianhua.text = [NSString stringWithFormat:@"%@",shrdh];
        if (dic[@"postCode"] == nil||[dic[@"postCode"] isEqualToString:@""]) {
            shryb = @"";
        }else{
            shryb = dic[@"postCode"];
        }
        self.youbian.text = [NSString stringWithFormat:@"%@",shryb];
        if (dic[@"streetName"] == nil||[dic[@"streetName"] isEqualToString:@""]) {
            shrdz = @"";
        }else{
            shrdz = dic[@"streetName"];
        }
        self.dizhi.text = [NSString stringWithFormat:@"%@",shrdz];
        if (dic[@"provinceName"] == nil||[dic[@"provinceName"] isEqualToString:@""]) {
            shrsf = @"";
        }else{
            shrsf = dic[@"provinceName"];
        }
        s = [NSString stringWithFormat:@"%@",shrsf];
        if (dic[@"cityName"] == nil||[dic[@"cityName"] isEqualToString:@""]) {
            shrcs = @"";
        }else{
            shrcs = dic[@"cityName"];
        }
        city = [NSString stringWithFormat:@"%@",shrcs];
        if (dic[@"areaName"] == nil||[dic[@"areaName"] isEqualToString:@""]) {
            shrdq = @"";
        }else{
            shrdq = dic[@"areaName"];
        }
        quyu = [NSString stringWithFormat:@"%@",shrdq];
        [self xiala];
    }];
}
-(void)loading1{
    NSURL *url=[NSURL URLWithString:Kdizhi];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"id=%@",app._dizhiID];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
        NSString *shr;
        NSString *shrdh;
        NSString *shryb;
        NSString *shrsf;
        NSString *shrcs;
        NSString *shrdq;
        NSString *shrdz;
        if (dic[@"name"] == nil||[dic[@"name"] isEqualToString:@""]) {
            shr = @"";
        }else{
            shr = dic[@"name"];
        }
        self.name.text = [NSString stringWithFormat:@"%@",shr];
        if (dic[@"mobile"] == nil||[dic[@"mobile"] isEqualToString:@""]) {
            shrdh = @"";
        }else{
            shrdh = dic[@"mobile"];
        }
        self.dianhua.text = [NSString stringWithFormat:@"%@",shrdh];
        if (dic[@"postCode"] == nil||[dic[@"postCode"] isEqualToString:@""]) {
            shryb = @"";
        }else{
            shryb = dic[@"postCode"];
        }
        self.youbian.text = [NSString stringWithFormat:@"%@",shryb];
        if (dic[@"streetName"] == nil||[dic[@"streetName"] isEqualToString:@""]) {
            shrdz = @"";
        }else{
            shrdz = dic[@"streetName"];
        }
        self.dizhi.text = [NSString stringWithFormat:@"%@",shrdz];
        if (dic[@"provinceName"] == nil||[dic[@"provinceName"] isEqualToString:@""]) {
            shrsf = @"";
        }else{
            shrsf = dic[@"provinceName"];
        }
        s = [NSString stringWithFormat:@"%@",shrsf];
        if (dic[@"cityName"] == nil||[dic[@"cityName"] isEqualToString:@""]) {
            shrcs = @"";
        }else{
            shrcs = dic[@"cityName"];
        }
        city = [NSString stringWithFormat:@"%@",shrcs];
        if (dic[@"areaName"] == nil||[dic[@"areaName"] isEqualToString:@""]) {
            shrdq = @"";
        }else{
            shrdq = dic[@"areaName"];
        }
        quyu = [NSString stringWithFormat:@"%@",shrdq];
        [self xiala];
    }];
}
-(void)tianjia{
    [self xiala];
    ssq = [NSString stringWithFormat:@"%@%@%@",self.shengfen,self.shiqu,self.diyu];
    code2 = @"320582";
    NSURL *url=[NSURL URLWithString:tjxg];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"userId=%@&address=%@&postCode=%@&phone=%@&mobile=%@&name=%@&provinceId=%@&cityId=%@&areaId=%@&streetName=%@&longitude=%@&latitude=%@",app._id,ssq,self.youbian.text,sj,self.dianhua.text,self.name.text,code,code1,code2,self.dizhi.text,weidu,jingdu];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
    }];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    _alert =alert;
    [alert show];
}
-(void)xiugai{
    [self xiala];
    ssq = [NSString stringWithFormat:@"%@%@%@",self.shengfen,self.shiqu,self.diyu];
    code2 = @"320582";
    NSURL *url=[NSURL URLWithString:tjxg];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"id=%@&userId=%@&address=%@&postCode=%@&phone=%@&mobile=%@&name=%@&provinceId=%@&cityId=%@&areaId=%@&streetName=%@&longitude=%@&latitude=%@",self.goodsID,app._id,ssq,self.youbian.text,sj,self.dianhua.text,self.name.text,code,code1,code2,self.dizhi.text,weidu,jingdu];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
    }];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"修改成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    _alert = alert;
    [alert show];
}
-(void)shengbianhao{
    NSURL *url1=[NSURL URLWithString:Sheng];
    NSMutableURLRequest *request1=[NSMutableURLRequest requestWithURL:url1];
    NSString *postStr1=@"";
    [request1 setHTTPMethod:@"post"];
    NSData *data1=[postStr1 dataUsingEncoding:NSUTF8StringEncoding];
    [request1 setHTTPBody:data1];
    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        shengarray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:shengarray waitUntilDone:YES];
        for (NSDictionary *obj in shengarray) {
            NSString *ss = obj[@"name"];
            NSString *ss1 = obj[@"code"];
            code = ss1;
            [arr1 addObject:ss];
            [self shibianhao];
        }
        [self.tableview reloadData];
    }];

}
-(void)shibianhao{
    NSURL *url1=[NSURL URLWithString:Shi];
    NSMutableURLRequest *request1=[NSMutableURLRequest requestWithURL:url1];
    NSString *postStr1=[NSString stringWithFormat:@"parentId=%@",code];
    [request1 setHTTPMethod:@"post"];
    NSData *data1=[postStr1 dataUsingEncoding:NSUTF8StringEncoding];
    [request1 setHTTPBody:data1];
    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        shiarray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:shiarray waitUntilDone:YES];
        for (NSDictionary *obj in shiarray) {
            ssss = obj[@"name"];
            ssss1 = obj[@"code"];
            [arr2 addObject:ssss];
            [self xiala];
            if ([ssss  isEqual: self.shiqu]||[ssss isEqual:app.SHI]) {
            }
        }
        [self qubianhao];
        [self.tableview reloadData];
    }];
    
}
-(void)qubianhao{
    code1 = @"320500";
    NSURL *url1=[NSURL URLWithString:DiQu];
    NSMutableURLRequest *request1=[NSMutableURLRequest requestWithURL:url1];
    NSString *postStr1=[NSString stringWithFormat:@"parentId=%@",code1];
    [request1 setHTTPMethod:@"post"];
    NSData *data1=[postStr1 dataUsingEncoding:NSUTF8StringEncoding];
    [request1 setHTTPBody:data1];
    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        quarray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:quarray waitUntilDone:YES];
        for (NSDictionary *obj in quarray) {
            NSString *ss = obj[@"name"];
            NSString *ss1 = obj[@"code"];
            [self xiala];
            if ([ss isEqual:self.diyu]) {
                code2 = ss1;
            }
            [arr3 addObject:ss];
        }
        [self.tableview reloadData];
    }];
    
}
-(void)refreshData:(NSArray *)sender{
    self.tableview.dataSource = self;
    [self.tableview reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 262;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        UINib *nib=[UINib nibWithNibName:@"dituTableViewCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"bbbb"];
        static NSString *cellIdentifier = @"bbbb";
        dituTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        BMKMapView *mapview = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
    _mapview = mapview;
    if ([self.name.text isEqualToString:@"(null)"]) {
        [cell.queding setTitle:@"添加" forState:UIControlStateNormal];
    }else{
        [cell.queding setTitle:@"修改" forState:UIControlStateNormal];
    }
        [cell.queding addTarget:self action:@selector(qd) forControlEvents:UIControlEventTouchUpInside];
        [cell.quxiao addTarget:self action:@selector(qx) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:mapview];
        [cell addSubview:button];
        return cell;
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1&&alertView==_alert) {
        app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            goodsViewController *goods = [self.storyboard instantiateViewControllerWithIdentifier:@"goodsVC"];
            [self.navigationController pushViewController:goods animated:YES];
    }
}
-(void)qd{
    if ([self.name.text isEqualToString:@"(null)"]) {
        [self tianjia];
    }else{
        [self xiugai];
    }

}
-(void)qx{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [_mapview viewWillAppear];
    _mapview.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapview viewWillDisappear];
    _mapview.delegate = nil; // 不用时，置nil
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.name resignFirstResponder];
    [self.dianhua resignFirstResponder];
    [self.youbian resignFirstResponder];
    [self.dizhi resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
